//
//  TZVideoPlayerController.m
//  TZImagePickerController
//
//  Created by 谭真 on 16/1/5.
//  Copyright © 2016年 谭真. All rights reserved.
//

#import "TZVideoPlayerController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIView+Layout.h"
#import "TZImageManager.h"
#import "TZAssetModel.h"
#import "TZImagePickerController.h"
#import "TZPhotoPreviewController.h"
#import "SVProgressHUD.h"
#import "TZEditTextView.h"
#import "AppConst.h"
#import "TZEditTextToolBarView.h"
#import "IQKeyboardManager.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

#import <YYText/YYText.h>

@interface TZVideoPlayerController ()<TZEditTextToolBarViewDelegate,UITextViewDelegate> {
    AVPlayer *_player;
    AVPlayerLayer *_playerLayer;
    UIButton *_playButton;
    UIImage *_cover;
    
    
    UIButton *_doneButton;
    UIProgressView *_progress;
    
    UIStatusBarStyle _originStatusBarStyle;
    
    
    ///GPUImage
//    GPUImageMovie *movieFile;
//    GPUImageOutput<GPUImageInput> *filter;
//    GPUImageMovieWriter *movieWriter;
    CADisplayLink* dlink;
    
    ///AVFoundation
    AVAsset * videoAsset;
    AVAssetExportSession *exporter;
}
@property (assign, nonatomic) BOOL needShowStatusBar;
//@property (nonatomic,strong) UITextField *textField;
@property (nonatomic, strong) UIImageView *thumbImageView;
@property (nonatomic, strong) UIView *toolBar;
@property (nonatomic, strong) TZEditTextView *textView;
@property (nonatomic, strong) UIFont *mappedFont;
@property (nonatomic, strong) UIView *videoArea;
@property (nonatomic,strong) UIButton *coverbutton;
@property (nonatomic,strong) UIButton *closeButton;
@end

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

@implementation TZVideoPlayerController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_interactivePopDisabled = NO;
    self.fd_interactivePopMaxAllowedInitialDistanceToLeftEdge = 10;
    self.fd_prefersNavigationBarHidden = YES;
    [self.view addSubview:self.thumbImageView];
    
    self.needShowStatusBar = ![UIApplication sharedApplication].statusBarHidden;
    self.view.backgroundColor = [UIColor blackColor];
    TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
    if (tzImagePickerVc) {
        self.navigationItem.title = tzImagePickerVc.previewBtnTitleStr;
    }
    [self configMoviePlayer];
    
    NSString *path = [NSBundle bundleForClass:[self class]].resourcePath;
    NSString *bundlePath = [path stringByAppendingPathComponent:@"/SelectPhotosOrVideoContentViewLib.bundle"];
    NSBundle *resource_bundle = [NSBundle bundleWithPath:bundlePath];
    UIImage *image =[UIImage imageNamed:@"videoBack1" inBundle:resource_bundle compatibleWithTraitCollection:nil];
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    closeButton.frame = CGRectMake(5, StatusBarHeight+5, 44, 44);
    [closeButton setImage:image forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeButton];
    self.closeButton = closeButton;
}
-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _originStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    TZEditTextToolBarView *inputCommentView = [TZEditTextToolBarView startMonitoring];
    inputCommentView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = _originStatusBarStyle;
    [TZEditTextToolBarView stopMonitoring];
    [self.textView resignFirstResponder];
    [SVProgressHUD dismiss];
}

- (void)configMoviePlayer {
    
    [[TZImageManager manager] getPhotoWithAsset:_model.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
        if (!isDegraded && photo) {
            dispatch_async(dispatch_get_main_queue(), ^{
            self->_cover = photo;
            self->_doneButton.enabled = YES;
                self.thumbImageView.image = photo;});
        }
    }];
  
    [[TZImageManager manager] getVideoWithAsset:_model.asset completion:^(AVPlayerItem *playerItem, NSDictionary *info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->_player = [AVPlayer playerWithPlayerItem:playerItem];
            self->_playerLayer = [AVPlayerLayer playerLayerWithPlayer:self->_player];
            self->_playerLayer.frame = self.thumbImageView.frame;
//            self->_playerLayer.borderColor = [UIColor redColor].CGColor;
//            self->_playerLayer.borderWidth = 4;
            //[self.view.layer addSublayer:self->_playerLayer];
            [self.view.layer insertSublayer:self->_playerLayer above:self.thumbImageView.layer];
            [self addProgressObserver];
            
            //[self configPlayButton];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
            [tap addTarget:self action:@selector(startEndEditing)];
            [self.view addGestureRecognizer:tap];
            
            [self configBottomToolBar];
            
            //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:self->_player.currentItem];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playButtonClick) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
            [self playButtonClick];
        });
    }];
}
-(void)startEndEditing{
    [self.textView resignFirstResponder];
    if (self.textView.text.length==0) {
        [self.videoArea removeFromSuperview];
    }
    //[self.view endEditing:YES];
}
/// Show progress，do it next time / 给播放器添加进度更新,下次加上
- (void)addProgressObserver{
    AVPlayerItem *playerItem = _player.currentItem;
    UIProgressView *progress = _progress;
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds([playerItem duration]);
        if (current) {
            [progress setProgress:(current/total) animated:YES];
        }
    }];
}

- (void)configPlayButton {
//    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    //[_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlay"] forState:UIControlStateNormal];
//    //[_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlayHL"] forState:UIControlStateHighlighted];
//    [_playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_playButton];
}
//-(UITextField*)textField{
//    if (!_textField) {
//        _textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
//        _textField.center = self.view.center;
//        _textField.font = [UIFont systemFontOfSize:40];
//        [self.view addSubview:_textField];
//        _textField.backgroundColor = [MainBackGroudColor colorWithAlphaComponent:0.6];
//    }
//    return _textField;
//}
- (void)configBottomToolBar {
    
    
    
    [self.view addSubview:self.toolBar];
    
    
}
-(UIView*)toolBar{
    if (!_toolBar) {
        _toolBar = [[UIView alloc] initWithFrame:CGRectZero];
        //CGFloat rgb = 34 / 255.0;
        _toolBar.backgroundColor = [UIColor blackColor]; //[UIColor colorWithRed:rgb green:rgb blue:rgb alpha:0.7];
        
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
        if (!_cover) {
            _doneButton.enabled = NO;
        }
        _doneButton.backgroundColor = MainBackGroudColor;
        [_doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
        TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
        if (tzImagePickerVc) {
            [_doneButton setTitle:tzImagePickerVc.doneBtnTitleStr forState:UIControlStateNormal];
            [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorNormal forState:UIControlStateNormal];
        } else {
            [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
            [_doneButton setTitleColor:MainColor forState:UIControlStateNormal];
        }
        [_doneButton setTitleColor:tzImagePickerVc.oKButtonTitleColorDisabled forState:UIControlStateDisabled];
        [_toolBar addSubview:_doneButton];
        
        UIButton *addTextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [addTextButton setTitle:@"添加文字" forState:UIControlStateNormal];
        [addTextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        addTextButton.frame = CGRectMake(12, 0, 80, 44);
        [addTextButton addTarget:self action:@selector(addTextButtonAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_toolBar addSubview:addTextButton];
        
        if (tzImagePickerVc.videoPreviewPageUIConfigBlock) {
            tzImagePickerVc.videoPreviewPageUIConfigBlock(_playButton, _toolBar, _doneButton);
        }
    }
    return _toolBar;
}

-(void)addTextButtonAction{
    
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       [IQKeyboardManager sharedManager].enable = NO;
       [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
       if (self.videoArea.superview == nil) {
           //[self.view addSubview:self.videoArea ];
           [self.view insertSubview:self.videoArea belowSubview:self.closeButton];
       
       }
       if (self.textView.superview == nil) {
           [self.videoArea addSubview:self.textView];
       
       }
       self.textView.editable = YES;
       [self.textView becomeFirstResponder];
   });
    
//NSLog(@"%f,%f,%f,%f",self.view.frame.origin.x,self.view.frame.origin.y,self.view.frame.size.width,self.view.frame.size.height); NSLog(@"%f,%f,%f,%f",_playerLayer.videoRect.origin.x,_playerLayer.videoRect.origin.y,_playerLayer.videoRect.size.width,_playerLayer.videoRect.size.height);
//NSLog(@"%f,%f,%f,%f",_playerLayer.visibleRect.origin.x,_playerLayer.visibleRect.origin.y,_playerLayer.visibleRect.size.width,_playerLayer.visibleRect.size.height);
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    TZImagePickerController *tzImagePicker = (TZImagePickerController *)self.navigationController;
    if (tzImagePicker && [tzImagePicker isKindOfClass:[TZImagePickerController class]]) {
        return tzImagePicker.statusBarStyle;
    }
    return [super preferredStatusBarStyle];
}

#pragma mark - Layout

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    CGFloat statusBarHeight = StatusBarHeight; //[TZCommonTools tz_statusBarHeight];
    CGFloat navBarHeight = NavigationBarHeight; //self.navigationController.navigationBar.tz_height;
    CGFloat statusBarAndNaviBarHeight = statusBarHeight + navBarHeight;
    CGFloat toolBarHeight = [TZCommonTools tz_isIPhoneX] ? 44 + (83 - 49) : 44;
    
    self.thumbImageView.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - toolBarHeight);
//    self.view.layer.borderColor = [UIColor yellowColor].CGColor;
//    self.view.layer.borderWidth = 2;
    
    _playerLayer.frame = self.thumbImageView.frame;
//    _playerLayer.borderColor = [UIColor redColor].CGColor;
//    _playerLayer.borderWidth = 4;
    
    self.toolBar.frame = CGRectMake(0, SCREENHEIGHT - toolBarHeight, SCREENWIDTH, toolBarHeight);
    _doneButton.frame = CGRectMake(self.view.tz_width - 44 - 12, 0, 44, 44);
    
    _doneButton.layer.masksToBounds = YES;
    _doneButton.layer.cornerRadius = _doneButton.frame.size.height/2.0;
    
    _playButton.frame = CGRectMake(0, statusBarAndNaviBarHeight, self.view.tz_width, self.view.tz_height - statusBarAndNaviBarHeight - toolBarHeight);
    
    TZImagePickerController *tzImagePickerVc = (TZImagePickerController *)self.navigationController;
    if (tzImagePickerVc.videoPreviewPageDidLayoutSubviewsBlock) {
        tzImagePickerVc.videoPreviewPageDidLayoutSubviewsBlock(_playButton, self.toolBar, _doneButton);
    }
}

#pragma mark - Click Event

- (void)playButtonClick {
    CMTime currentTime = _player.currentItem.currentTime;
    CMTime durationTime = _player.currentItem.duration;
    if (_player.rate == 0.0f) {
        if (currentTime.value == durationTime.value) [_player.currentItem seekToTime:CMTimeMake(0, 1)];
        [_player play];
//        [self.navigationController setNavigationBarHidden:YES];
//        _toolBar.hidden = YES;
//        [_playButton setImage:nil forState:UIControlStateNormal];
//        [UIApplication sharedApplication].statusBarHidden = YES;
    } else {
        [self pausePlayerAndShowNaviBar];
    }
}

- (void)doneButtonClick {
    
    _doneButton.userInteractionEnabled  = NO;
    PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    options.networkAccessAllowed = YES;
    [[PHImageManager defaultManager] requestAVAssetForVideo:_model.asset options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
             NSLog(@"Info:\n%@",info);
            AVURLAsset *videoAsset1 = (AVURLAsset*)avasset;
             NSLog(@"AVAsset URL: %@",videoAsset1.URL);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self startWithPathURL:videoAsset1.URL];
        });
     }];
    
    
//    if (self.navigationController) {
//        TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
//        if (imagePickerVc.autoDismiss) {
//            [self.navigationController dismissViewControllerAnimated:YES completion:^{
//                [self callDelegateMethod];
//            }];
//        } else {
//            [self callDelegateMethod];
//        }
//    } else {
//        [self dismissViewControllerAnimated:YES completion:^{
//            [self callDelegateMethod];
//        }];
//    }
}

-(void)startWithPathURL:(NSURL*)videoPath{
    
    if (!videoPath) {
        return;
    }

    //1 创建AVAsset实例 AVAsset包含了video的所有信息 self.videoUrl输入视频的路径
    
    //封面图片
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    videoAsset = [AVURLAsset URLAssetWithURL:videoPath options:opts];     //初始化视频媒体文件
    
    CMTime startTime = CMTimeMakeWithSeconds(0.2, 600);
    CMTime endTime = CMTimeMakeWithSeconds(videoAsset.duration.value/videoAsset.duration.timescale-0.2, videoAsset.duration.timescale);
    
    //声音采集
    AVURLAsset * audioAsset = [[AVURLAsset alloc] initWithURL:videoPath options:opts];
    
    //2 创建AVMutableComposition实例. apple developer 里边的解释 【AVMutableComposition is a mutable subclass of AVComposition you use when you want to create a new composition from existing assets. You can add and remove tracks, and you can add, remove, and scale time ranges.】
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    
    //3 视频通道  工程文件中的轨道，有音频轨、视频轨等，里面可以插入各种对应的素材
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];
    //把视频轨道数据加入到可变轨道中 这部分可以做视频裁剪TimeRange
    [videoTrack insertTimeRange:CMTimeRangeFromTimeToTime(startTime, endTime)
                        ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
                         atTime:kCMTimeZero error:nil];
    //音频通道
    AVMutableCompositionTrack * audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    //音频采集通道
    AVAssetTrack * audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    [audioTrack insertTimeRange:CMTimeRangeFromTimeToTime(startTime, endTime) ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];
    
    //3.1 AVMutableVideoCompositionInstruction 视频轨道中的一个视频，可以缩放、旋转等
    AVMutableVideoCompositionInstruction *mainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    mainInstruction.timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, videoTrack.timeRange.duration);
    
    // 3.2 AVMutableVideoCompositionLayerInstruction 一个视频轨道，包含了这个轨道上的所有视频素材
    AVMutableVideoCompositionLayerInstruction *videolayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
    AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    //    UIImageOrientation videoAssetOrientation_  = UIImageOrientationUp;
    BOOL isVideoAssetPortrait_  = NO;
    CGAffineTransform videoTransform = videoAssetTrack.preferredTransform;
    if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) {
        //        videoAssetOrientation_ = UIImageOrientationRight;
        isVideoAssetPortrait_ = YES;
    }
    if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) {
        //        videoAssetOrientation_ =  UIImageOrientationLeft;
        isVideoAssetPortrait_ = YES;
    }
    //    if (videoTransform.a == 1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == 1.0) {
    //        videoAssetOrientation_ =  UIImageOrientationUp;
    //    }
    //    if (videoTransform.a == -1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == -1.0) {
    //        videoAssetOrientation_ = UIImageOrientationDown;
    //    }
    [videolayerInstruction setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];
    [videolayerInstruction setOpacity:0.0 atTime:endTime];
    // 3.3 - Add instructions
    mainInstruction.layerInstructions = [NSArray arrayWithObjects:videolayerInstruction,nil];
    //AVMutableVideoComposition：管理所有视频轨道，可以决定最终视频的尺寸，裁剪需要在这里进行
    AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
    
    CGSize naturalSize;
    if(isVideoAssetPortrait_){
        naturalSize = CGSizeMake(videoAssetTrack.naturalSize.height, videoAssetTrack.naturalSize.width);
    } else {
        naturalSize = videoAssetTrack.naturalSize;
    }
    
    NSString *path = [NSBundle bundleForClass:[self class]].resourcePath;
    NSString *bundlePath = [path stringByAppendingPathComponent:@"/SelectPhotosOrVideoContentViewLib.bundle"];
    NSBundle *resource_bundle = [NSBundle bundleWithPath:bundlePath];
    UIImage *image = [UIImage imageNamed:@"watermark" inBundle:resource_bundle
           compatibleWithTraitCollection:nil];
    
    
    float renderWidth, renderHeight;
    renderWidth = naturalSize.width;
    renderHeight = naturalSize.height;
    mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight);
    mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight);
    mainCompositionInst.instructions = [NSArray arrayWithObject:mainInstruction];
    mainCompositionInst.frameDuration = CMTimeMake(1, 25);
    [self applyVideoEffectsToComposition:mainCompositionInst WithWaterImg:image WithCoverImage:image WithQustion:self.textView.text size:CGSizeMake(renderWidth, renderHeight)];
    
    // 4 - 输出路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]]];
    unlink([myPathDocs UTF8String]);
    NSURL* videoUrl = [NSURL fileURLWithPath:myPathDocs];
    
    
    // 5 - 视频文件输出
    
    exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=videoUrl;
    exporter.outputFileType = AVFileTypeQuickTimeMovie;
    exporter.shouldOptimizeForNetworkUse = YES;
    exporter.videoComposition = mainCompositionInst;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //这里是输出视频之后的操作，做你想做的
            [self exportDidFinish:self->exporter];
        });
    }];
    
    dlink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgress)];
    [dlink setFrameInterval:15];
    [dlink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [dlink setPaused:NO];

}
- (void)exportDidFinish:(AVAssetExportSession*)session {
    if (session.status == AVAssetExportSessionStatusCompleted) {
        NSURL *outputURL = session.outputURL;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __block PHObjectPlaceholder *placeholder;
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL.path)) {
                NSError *error;
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:outputURL];
                    placeholder = [createAssetRequest placeholderForCreatedAsset];
                } error:&error];
                if (error) {
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error]];
                }
                else{
                    if (self.delegate) {
                        [self.delegate exportDidFinishIn:self];
                    }
                    [SVProgressHUD dismiss];
                    //[SVProgressHUD showSuccessWithStatus:@"视频已经保存到相册"];
                }
            }else {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"视频保存相册失败，请设置软件读取相册权限", nil)];
            }
        });
    }
}
- (void)applyVideoEffectsToComposition:(AVMutableVideoComposition *)composition WithWaterImg:(UIImage*)img WithCoverImage:(UIImage*)coverImg WithQustion:(NSString*)textInputed  size:(CGSize)size {
    
    
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGFloat lineHeightInVideo = (self.textView.font.lineHeight/self.videoArea.bounds.size.height)*size.height;
    
    CGFloat fontSize = 5.0;
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    
    while (font.lineHeight<lineHeightInVideo) {
        fontSize += 0.01;
        font = [UIFont systemFontOfSize:fontSize];
    }
    
    CGFloat X,Y;//W,H;
    X = ceilf((self.textView.frame.origin.x/self.videoArea.bounds.size.width)*size.width);
    Y = ceilf((self.textView.frame.origin.y/self.videoArea.bounds.size.height)*size.height);
//    W = ceilf((self.textView.bounds.size.width/self.videoArea.bounds.size.width)*size.width);
//    H = ceilf((self.textView.bounds.size.height/self.videoArea.bounds.size.height)*size.height);

    CGFloat lineSpacing;
    lineSpacing = (5.0/self.videoArea.bounds.size.height)*size.height;
    CGFloat gap;
    gap = ((self.textView.textContainerInset.top+self.textView.textContainerInset.bottom)/self.videoArea.bounds.size.height)*size.height;

    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle alloc] init];
    textStyle.lineBreakMode = NSLineBreakByWordWrapping;
    //textStyle.alignment = NSTextAlignmentCenter;
    textStyle.lineSpacing = lineSpacing;
    textStyle.firstLineHeadIndent = 0.0;
    textStyle.headIndent = 0.0;
    textStyle.tailIndent = 0.0;
    textStyle.minimumLineHeight = font.lineHeight;
    textStyle.maximumLineHeight = font.lineHeight;
    textStyle.paragraphSpacing = 0;
    textStyle.paragraphSpacingBefore = 0.0f;
    textStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
    textStyle.lineHeightMultiple = 1.0;
    textStyle.hyphenationFactor = 1;

    NSMutableDictionary *textAttributes = [[NSMutableDictionary alloc] init];
    [textAttributes setValue:textStyle forKey:NSParagraphStyleAttributeName];
    [textAttributes setValue:font forKey:NSFontAttributeName];

    [textAttributes setValue:self.textView.textColor forKey:NSForegroundColorAttributeName];
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:textInputed];
    [attributedText setAttributes:textAttributes range:NSMakeRange(0, textInputed.length)];
    
    CGSize textSize = [attributedText.string boundingRectWithSize:CGSizeMake(size.width-2*kEdgeIntegral*scale, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:textAttributes context:nil].size;
    CGFloat textWidth = ceilf(textSize.width);
    CGFloat textheight = ceilf(textSize.height);
    
    YYLabel *textView = [YYLabel new];
    textView.attributedText = attributedText;
    //textView.textAlignment = NSTextAlignmentCenter;
    textView.lineBreakMode = NSLineBreakByWordWrapping;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(textWidth, CGFLOAT_MAX) text:attributedText];
    textView.textLayout = textLayout;
    textView.numberOfLines = 0;
    textWidth = textLayout.textBoundingSize.width;
    textheight = textLayout.textBoundingSize.height+gap;
    textView.frame = CGRectMake(X, size.height - Y - textheight, textWidth, textheight);
    textView.backgroundColor = self.textView.backgroundColor;
    
    textView.layer.masksToBounds = YES;
    textView.layer.cornerRadius = textView.frame.size.height/10.0>20?20:(textView.frame.size.height/10.0);
    [self.videoArea addSubview:textView];

    CALayer *imgLayer = [CALayer layer];
    imgLayer.contents = (id)img.CGImage;
    imgLayer.contentsScale = scale;
    CGFloat waterCoverWidth = size.width/9.0;
    CGFloat waterCoverHeight = waterCoverWidth/2.0;
    imgLayer.frame = CGRectMake(size.width-waterCoverWidth-waterCoverHeight/5.0, size.height-waterCoverHeight-waterCoverHeight/5.0, waterCoverWidth,waterCoverHeight);
    
    CABasicAnimation *anima = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    anima.fromValue = [NSNumber numberWithFloat:1.0f];
    anima.toValue = [NSNumber numberWithFloat:1.4f];
    anima.repeatCount = MAXFLOAT;
    anima.duration = 1.0f;
    [anima setAutoreverses:YES];
    [anima setRemovedOnCompletion:NO];
    [anima setFillMode:kCAFillModeForwards];
    anima.beginTime = AVCoreAnimationBeginTimeAtZero;
    [imgLayer addAnimation:anima forKey:@"scaleAniamtion"];
    
 
    CALayer *overlayLayer = [CALayer layer];
    
    if(textInputed&&textInputed.length>0){
        [overlayLayer addSublayer:textView.layer];
        
    }
    [overlayLayer addSublayer:imgLayer];
    overlayLayer.frame = CGRectMake(0, 0, size.width, size.height);
    [overlayLayer setMasksToBounds:YES];
    
    CALayer *videoLayer = [CALayer layer];
    videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
    CALayer *parentLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:overlayLayer];
    
    composition.animationTool = [AVVideoCompositionCoreAnimationTool
                                 videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    
}
- (UIImage*)convertViewToImage:(UIView*)view {

    UIImage*imageRet = [[UIImage alloc] init];
    UIGraphicsBeginImageContextWithOptions(view.frame.size,YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageRet;
}

-(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font constraintSize:(CGSize)constraintSize
{
    CGSize stringSize = CGSizeZero;

    NSDictionary *attributes = @{NSFontAttributeName:font};
    NSInteger options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect stringRect = [string boundingRectWithSize:constraintSize options:options attributes:attributes context:NULL];
    stringSize = stringRect.size;

    return stringSize;
}

//更新生成进度
- (void)updateProgress {
    [SVProgressHUD showProgress:exporter.progress status:@"处理中..."];
    if (exporter.progress>=1.0) {
        [dlink setPaused:true];
        [dlink invalidate];
        [SVProgressHUD dismiss];
        _doneButton.userInteractionEnabled  = YES;
    }
}
- (void)callDelegateMethod {
    TZImagePickerController *imagePickerVc = (TZImagePickerController *)self.navigationController;
    if ([imagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingVideo:sourceAssets:)]) {
        [imagePickerVc.pickerDelegate imagePickerController:imagePickerVc didFinishPickingVideo:_cover sourceAssets:_model.asset];
    }
    if (imagePickerVc.didFinishPickingVideoHandle) {
        imagePickerVc.didFinishPickingVideoHandle(_cover,_model.asset);
    }
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    self.coverbutton.hidden = YES;
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithDictionary:textView.typingAttributes];
    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    para.lineBreakMode = NSLineBreakByCharWrapping;
    [dic1 setValue:para forKey:NSParagraphStyleAttributeName];
    textView.typingAttributes = dic1;
        
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    self.textView.editable = NO;
    self.coverbutton.hidden = NO;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString:@"\n"]){

        [self.textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)changeTextColor:(UIColor *)color{
    
    self.textView.textColor = color;
    
}

- (void)changeBackgroundColor:(UIColor *)color{
    
    self.textView.backgroundColor = color;
    
}

#pragma mark - Notification Method

- (void)pausePlayerAndShowNaviBar {
    [_player pause];
    _toolBar.hidden = NO;
    //[self.navigationController setNavigationBarHidden:NO];
    //[_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlay"] forState:UIControlStateNormal];
    
//    if (self.needShowStatusBar) {
//        [UIApplication sharedApplication].statusBarHidden = NO;
//    }
}
- (void)panAction:(UIPanGestureRecognizer *)recognizer {
    CGPoint translationPoint = [recognizer translationInView:self.videoArea];
    CGPoint center = recognizer.view.center;
    recognizer.view.center = CGPointMake(center.x + translationPoint.x, center.y + translationPoint.y);
    [recognizer setTranslation:CGPointZero inView:self.videoArea];
    self.textView.frame = self.coverbutton.frame;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UIImageView *)thumbImageView {
    if (!_thumbImageView) {
        _thumbImageView = [UIImageView new];
        NSLog(@"StatusBarHeight:%f,%f",StatusBarHeight,NavigationBarHeight);
        _thumbImageView.frame = CGRectMake(0, StatusBarHeight, SCREENWIDTH, self.view.bounds.size.height-StatusBarHeight-self.toolBar.bounds.size.height);
        _thumbImageView.contentMode = UIViewContentModeScaleAspectFit;
        _thumbImageView.layer.masksToBounds = YES;
    }
    return _thumbImageView;
}
#pragma clang diagnostic pop
- (TZEditTextView *)textView {
    if (!_textView) {
        
        UIFont *font = [UIFont systemFontOfSize:25];
        _textView = [[TZEditTextView alloc] init];
        _textView.delegate = self;
        //_textView.textContainerInset = UIEdgeInsetsMake(5, 0, 5, 0);
        _textView.frame = CGRectMake(self.videoArea.frame.origin.x + (self.videoArea.frame.size.width-10)/2.0, 20 , 20, font.lineHeight+_textView.textContainerInset.top+_textView.textContainerInset.bottom);
        _textView.font = font;
        _textView.backgroundColor = [UIColor clearColor];
        _textView.textColor = [UIColor whiteColor];
        WEAK_SELF(weakSelf)
        _textView.textChangedBlock = ^(CGRect frame) {
            STRONG_SELF(strongSelf)
            strongSelf.coverbutton.frame = frame;
//            NSLog(@"文本框在屏幕中的尺寸:%f,%f,%f",frame.size.width,frame.size.height,strongSelf->_textView.font.lineHeight);
            if (strongSelf.coverbutton.superview==nil) {
                [strongSelf.videoArea addSubview:strongSelf.coverbutton];
            }
            
        };
        

        _textView.textAlignment = NSTextAlignmentCenter;
//        _textView.layer.cornerRadius = 4;
//        _textView.layer.borderWidth = 1;
//        _textView.layer.borderColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.89 alpha:1.00].CGColor;
        //_textView.delegate = self;
        _textView.returnKeyType = UIReturnKeyDone;
        
        
        
        
    }
    return _textView;
}
-(UIView*)videoArea{
    if (!_videoArea) {
        CGFloat X,Y;
        X = _playerLayer.frame.origin.x+_playerLayer.videoRect.origin.x;
        Y = _playerLayer.frame.origin.y+_playerLayer.videoRect.origin.y;
        
        _videoArea = [[UIView alloc]initWithFrame:CGRectMake(X, Y, _playerLayer.videoRect.size.width, _playerLayer.videoRect.size.height)];
        //_videoArea.backgroundColor = [UIColor yellowColor];
        _videoArea.userInteractionEnabled  = YES;
//        _videoArea.layer.borderWidth = 4;
//        _videoArea.layer.borderColor = [UIColor brownColor].CGColor;
    }
    return _videoArea;
}

-(UIButton*)coverbutton{
    if (!_coverbutton) {
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        _coverbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        _coverbutton.hidden = YES;
        [_coverbutton addTarget:self action:@selector(addTextButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _coverbutton.backgroundColor = [UIColor clearColor];
        [_coverbutton addGestureRecognizer:panGesture];
    }
    return _coverbutton;
}
@end
